#encoding=utf-8
from email.mime.text import MIMEText  #添加正文类
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart   #添加附件类
import smtplib
from email.header import Header
from setLog import Logger
from email.mime.image import MIMEImage  #添加图片类
import os

mylogger = Logger(logger="sendMail").get_log()
class sendMail():

    def mail(self,body):


        # 发送方邮箱地址和口令
        from_addr = '185365234@qq.com'
        passwd ='nbtrxpitvofxbjha' # QQ邮箱需要输入授权码，不含空格
        # 发送方邮箱的smtp服务器地址
        smtp_server = 'smtp.qq.com'
        # 收件方地址
        to_addr ='sunyanfen@myhexin.com'


        #支持多部分
        msg=MIMEMultipart('alternative')
        # 构造纯文本邮件
        msgText=MIMEText('你好，附件是自动化测试报告，请查收！', 'plain', 'utf-8')  #MIMEText的参数：一是邮件正文；二是subtype，‘plain’表示传入纯文本；三是编码类型；
        msg.attach(msgText)

        # # 构造正文为html的邮件
        # with open('D:\\pypronjects\\tzzb-AppiumUI\\result\\html\\2018-11-21 21-28-38---result.html','rb') as f:
        #     msg=MIMEText(f.read(),_subtype='html',_charset='utf-8')   #转化成html的格式显示，在邮件中看起来更像是一张截图，哈哈哈哈
        #     f.close()


        # 构造HTML的附件
        # path='D:\\pypronjects\\tzzb-AppiumUI\\result\\html\\2018-11-21 21-28-38---result.html'
        add=MIMEText(body,'html', 'utf-8')
        add['Content-Type']='application/octet-stream'  #转化成二进制流
        add["Content-Disposition"] = 'attachment; filename="自动化测试报告.html"'  #自定义命名
        msg.attach(add)


        # # 添加图片附件
        # path='D:\\pypronjects\\tzzb-AppiumUI\\result\\screenshot\\2018-11-24\\shouye-Login(15619205143).png'
        # with open(path,'rb') as f:
        #     msgImg=MIMEMultipart(f.read())
        #     name=os.path.basename(path)
        #     print(name)
        #     f.close()
        #     msgImg["Content-Disposition"] = 'attachment; filename=%s',name
        #
        # msg.attach(msgImg)


        # 编辑邮件的头部信息f
        msg['From'] = Header('孙毛线<%s>' % from_addr, 'utf-8')
        msg['To'] = Header('sunyanfen<%s>' % to_addr, 'utf-8')
        msg['Subject'] = Header('投资账本自动化运行结果', 'utf-8').encode()



        #发送过程
        try:
            server = smtplib.SMTP_SSL(smtp_server, 465)  # 注意：需要建立ssl安全连接，更安全；465是QQ邮箱的smtp端口
            server.set_debuglevel(1)  # 打印smtp服务器的交互信息,直接赋值打印出来是none的，一般默认不输出0
            server.login(from_addr, passwd)  #登录smtp服务器
            server.sendmail(from_addr, to_addr, msg.as_string())  # 把MIMEText转化成str .as_string()
            server.quit()
            # print("邮件发送成功")
            mylogger.debug("邮件发送成功")
        except smtplib.SMTPException, e:
            # print e
            mylogger.debug(e)




if __name__ == '__main__':
    a=sendMail()
    a.mail()



